import React, { createRef } from 'react'
import { Button, Form, Divider } from 'antd'
import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import DataTable from '@components/Tables'
import request from '@utils/request'
import { withTranslation } from 'react-i18next'
import moment from 'moment-mini'
import { RowAction, Expand, SearchField } from '@components/Tables/types'
import Modal from '@components/Modal'
import TableDropdown from '@components/Tables/Dropdown'
import Update from './pop/update'
import Create from './pop/create'

import apis from '@http/apis'

const searchFields: SearchField[] = [
  {
    label: '输入框',
    name: 'id',
    type: 'input',
    validationRule: {},
    payload: {
      props: {
        placeholder: 'placeholder',
      },
    },
  },
  {
    label: '下拉框',
    name: 'sys_dict_id',
    type: 'select',
    validationRule: {},
    payload: {
      options: [
        { key: '0', label: '全部', value: '' },
        { key: '1', label: '大数据', value: '1' },
        { key: '2', label: '云计算', value: '2' },
        { key: '4', label: '编程语言', value: '4' },
      ],
    },
  },

  {
    label: '树形选择',
    name: 'treeselect',
    type: 'treeSelect',
    validationRule: {
      required: false,
    },
    payload: {
      props: {
        treeData: [
          {
            title: 'Node1',
            value: '0-0',
            children: [
              {
                title: 'Child Node1',
                value: '0-0-1',
              },
              {
                title: 'Child Node2',
                value: '0-0-2',
              },
            ],
          },
          {
            title: 'Node2',
            value: '0-1',
          },
        ],
      },
    },
  },
  {
    label: '日期',
    name: 'datapicker',
    type: 'datePicker',
    validationRule: {
      required: false,
    },
    payload: {
      props: {},
    },
  },
]

const columns = [
  {
    key: 'id',
    title: 'ID',
    dataIndex: 'id',
  },
  {
    key: 'name',
    title: '名称',
    dataIndex: 'name',
    render(value: string, row: any) {
      return (
        value && (
          <a
            href={`https://www.shuidilab.cn/portal/classdetails/${row.group_id}_${row.id}`}
          >
            {value}
          </a>
        )
      )
    },
  },
  {
    key: 'created_at',
    title: '创建时间',
    dataIndex: 'created_at',
    render(value: string) {
      return value && `${moment(value).format('YYYY-MM-DD HH:mm:ss')}`
    },
  },
]

const expands: Expand[] = [
  {
    title: '简介：',
    dataIndex: 'c_intro',
    render(value:any) {
      return value && `${value.substr(0, 100)} ...`
    },
  },
  {
    title: '目标：',
    dataIndex: 'c_goal',
  },
]

const onSearch = async ({ page, pageSize, values }: any) => {
  const res = await request.get(apis.getContentLists, {
    params: {
      page_index: page,
      page_size: pageSize,
      ...values,
    },
  })
  return {
    dataSource: res.data.course_list,
    total: Number(res.data.page_counts * pageSize),
  }
}

interface IProps {
  t?: any
}

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
@withTranslation()
class News extends React.Component<IProps> {
  dataTableRef: any
  saveDataTableRef: any
  popCreateRef: any
  popUpdateRef: any
  constructor(props: any) {
    super(props)
    this.dataTableRef = null
    this.saveDataTableRef = (ref: DataTable) => {
      this.dataTableRef = ref
    }
    this.popCreateRef = createRef()
    this.popUpdateRef = createRef()
  }

  componentDidMount() {
    if (this.dataTableRef) {
      this.dataTableRef.fetch(1)
    }
  }

  delete = (selectedRows: any) => {
    Modal.confirm({
      centered: true,
      title: '删除',
      content: '确定删除？',
      okText: '确认',
      cancelText: '取消',
      icon: <ExclamationCircleOutlined />,
      okType: 'danger',
      onOk() {
        return new Promise((resolve, reject) => {
          setTimeout(resolve, 3000)
        })
      },
    })
  }

  renderActions = () => {
    const that = this
    const actions: RowAction[] = [
      {
        label: '编辑',
        action(record: any) {
          that.popUpdateRef.current.show([record])
        },
      },
      {
        label: '更多',
        children: [
          {
            label: '删除',
            action(record: any) {
              that.delete([record])
            },
          },
          {
            label: '打开',
            action(record: any) {
              console.warn(record)
            },
          },
        ],
      },
    ]

    return actions
  }

  CreateBtn = () => {
    const create = () => {
      this.popCreateRef.current.show()
    }
    return (
      <Button type="primary" onClick={create} icon={<PlusOutlined />}>
        创建
      </Button>
    )
  }

  renderPlugin = () => {
    const that = this
    return [
      {
        renderer(selectedRowKeys: any, selectedRows: any, clearSelection: any) {
          return that.CreateBtn()
        },
      },
      {
        renderer(selectedRowKeys: any, selectedRows: any, clearSelection: any) {
          const data = [
            {
              label: '编辑',
              icon: <EditOutlined />,
              disable: ((): boolean => {
                // 此函数只返回true,false
                if (selectedRows.length === 1) {
                  return false
                }
                return true
              })(),
              action() {
                that.popUpdateRef.current.show(selectedRows)
              },
            },
            {
              label: '删除',
              icon: <DeleteOutlined />,
              disable: ((): boolean => {
                // 此函数只返回true,false
                if (selectedRows.length === 1) {
                  return false
                }
                return true
              })(),
              action() {
                that.delete(selectedRows)
              },
            },
          ]
          return (
            <TableDropdown
              data={data}
              selectedRows={selectedRows}
              clearSelection={clearSelection}
            />
          )
        },
      },
    ]
  }

  render(): any {
    return (
      <div>
        <DataTable
          name="contenttable"
          ref={this.saveDataTableRef}
          rowKey={(record) => record.id}
          showSearchFields={true}
          searchFields={searchFields}
          initialColumns={columns}
          initialExpands={expands}
          onSearch={onSearch}
          maxVisibleFieldCount={4}
          rowActions={this.renderActions()}
          plugins={this.renderPlugin()}
          searchBtnText="搜索"
          clearBtnText="取消"
          enableListSelection={true}
          listSelectionBtnText=""
          refresh={true}
        />
        <Update ref={this.popUpdateRef} />
        <Create ref={this.popCreateRef} />
      </div>
    )
  }
}

export default News